<html>

<head>
	<meta charset="utf-8">
	<title>计数排序</title>
	<script src="../../lib/d3.min.js" charset="utf-8"></script>
	<script src="../../lib/jquery-1.10.2.min.js"></script>
	<script src="./countSort.js"></script>
	<style>
		#bucket {
			position: relative;
			top: 10px;
		}

		div span {
			font-weight: bold
		}

		.bucketEle {
			border: 1px solid hsl(0, 100%, 50%);
			padding: 1px;
			background: gray;
			width: 30px;
			line-height: 30px;
			display: inline-block;
			text-align: center;
		}
	</style>
</head>

<body>
	数组：<input id="data" /> 格式：1,2,3,4,5,6,7,8,14,16,18,20,21,22

	<button onclick="generateData()">开始</button>
	<div id="main-svg">
	</div>

	<span>原始数组</span>
	<div id="orginal">


	</div>

	<span>计数数组</span>
	<div id="count">


	</div>

	<span>排序数组</span>
	<div id="sort">


	</div>

</body>
<script>

	function generateData() {
		var data = document.getElementById("data");

		if (data != null) {
			var array = data.value.split(",").map(Number);

			timerExe(array);


		}
	}
	function createArrShow(arr, dom,index) {

		var html = "<div>";
		for (var j = 0; arr != null && j < arr.length; j++) {
			if (index == j) {
				html += "<span class='bucketEle' style='background:red'>" + arr[j] + "</span>";
			} else {
				html += "<span class='bucketEle'>" + arr[j] + "</span>";
			}
			

		}
		html += "</div>";
		dom.append(html);
	}
	function drawBar(virtualArr) {
		var orginal = $("#orginal");
		var orginalArr = virtualArr.orginalArr;
		createArrShow(orginalArr, orginal,virtualArr.orginalIndex);

		var count = $("#count");
		var countArr = virtualArr.countArr;
		createArrShow(countArr, count,virtualArr.countIndex);

		var sort = $("#sort");
		var sortArr = virtualArr.sortArr;
		createArrShow(sortArr, sort,virtualArr.sortIndex);
	}

	function init() {
		//排序数组
		var array = [9, 5, 4, 3, 3, 2, 1];

		timerExe(array);
	}
	var timer = null;
	function timerExe(array) {
		if (timer != null) {
			clearInterval(timer);
		}
		var time = 1000; //多久执行一次排序
		//获取执行过程快照
		var virtualArr = countSort(array);
		console.log(virtualArr);
		var len = 0;
		timer = setInterval(function () {

			if (len == virtualArr.length) {
				clearInterval(timer);
			} else {
				//清除以前结果

				var doms = ["#orginal","#count","#sort"];
				for (var i=0;i<doms.length;i++) {
					var node = $(""+doms[i]);
					var childs = node.children();
					for (var j = 0; j < childs.length; j++) {
						childs[j].remove();
					}
				}
				drawBar(virtualArr[len]);

			}
			len++;
		}, time);
	}
	init();
</script>

</html>